package com.joker.orange.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.joker.common.constant.UserConstants;
import com.joker.common.core.domain.entity.SysDept;
import com.joker.common.core.domain.entity.SysUser;
import com.joker.common.core.page.TableDataInfo;
import com.joker.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.joker.common.helper.DataBaseHelper;
import com.joker.common.helper.LoginHelper;
import com.joker.common.utils.StreamUtils;
import com.joker.common.utils.StringUtils;
import com.joker.orange.domain.*;
import com.joker.orange.domain.bo.ShortVideoInfoBo;
import com.joker.orange.domain.bo.UserLikeBo;
import com.joker.orange.domain.vo.ShortVideoInfoVo;
import com.joker.orange.domain.vo.UserLikeVo;
import com.joker.orange.mapper.*;
import com.joker.orange.service.IBuyOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.joker.orange.domain.bo.VideoInfoBo;
import com.joker.orange.domain.vo.VideoInfoVo;
import com.joker.orange.service.IVideoInfoService;

import java.math.BigDecimal;
import java.util.*;

/**
 * 视频信息Service业务层处理
 *
 * @author Joker
 * @date 2024-06-09
 */
@RequiredArgsConstructor
@Service
public class VideoInfoServiceImpl implements IVideoInfoService {

    private final VideoInfoMapper baseMapper;
    private final CollectionMapper collectionMapper;
    private final UserLikeMapper userLikeMapper;
    private final IBuyOrderService buyOrderService;
    private final LongVideoCategoryMapper longVideoCategoryMapper;
    private final ShortVideoUserMapper shortVideoUserMapper;

    /**
     * 查询视频信息
     */
    @Override
    public VideoInfoVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询视频信息列表
     */
    @Override
    public TableDataInfo<VideoInfoVo> queryPageList(VideoInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<VideoInfo> lqw = buildQueryWrapper(bo);
        Page<VideoInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (VideoInfoVo record : result.getRecords()) {
            LongVideoCategory longVideoCategory = longVideoCategoryMapper.selectById(record.getCategoryId());
            record.setCategoryName(longVideoCategory == null ? "" : longVideoCategory.getCategoryName());
            if ("1".equals(record.getVideoType())){
                ShortVideoUser shortVideoUser = shortVideoUserMapper.selectById(record.getShortVideoUserId());
                record.setShortVideoUserName(shortVideoUser == null ? "" : shortVideoUser.getUserName());
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询视频信息列表
     */
    @Override
    public List<VideoInfoVo> queryList(VideoInfoBo bo) {
        LambdaQueryWrapper<VideoInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<VideoInfo> buildQueryWrapper(VideoInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<VideoInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCategoryId() != null, VideoInfo::getCategoryId, bo.getCategoryId());
        lqw.eq(bo.getShortVideoUserId() != null, VideoInfo::getShortVideoUserId, bo.getShortVideoUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getVideoType()), VideoInfo::getVideoType, bo.getVideoType());
        lqw.eq(StringUtils.isNotBlank(bo.getVideoUrl()), VideoInfo::getVideoUrl, bo.getVideoUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getVideoCover()), VideoInfo::getVideoCover, bo.getVideoCover());
        lqw.eq(StringUtils.isNotBlank(bo.getVideoName()), VideoInfo::getVideoName, bo.getVideoName());
        lqw.eq(bo.getVideoTime() != null, VideoInfo::getVideoTime, bo.getVideoTime());
        lqw.eq(bo.getLikeNum() != null, VideoInfo::getLikeNum, bo.getLikeNum());
        lqw.eq(bo.getCollectNum() != null, VideoInfo::getCollectNum, bo.getCollectNum());
        lqw.eq(bo.getLookNum() != null, VideoInfo::getLookNum, bo.getLookNum());
        lqw.eq(StringUtils.isNotBlank(bo.getChargeType()), VideoInfo::getChargeType, bo.getChargeType());
        lqw.eq(bo.getConsumeDiamond() != null, VideoInfo::getConsumeDiamond, bo.getConsumeDiamond());
        lqw.eq(StringUtils.isNotBlank(bo.getVideoLabel()), VideoInfo::getVideoLabel, bo.getVideoLabel());
        lqw.eq(StringUtils.isNotBlank(bo.getIsTop()), VideoInfo::getIsTop, bo.getIsTop());
        lqw.orderByDesc(VideoInfo::getCreateTime);
        return lqw;
    }

    /**
     * 新增视频信息
     */
    @Override
    public Boolean insertByBo(VideoInfoBo bo) {
        VideoInfo add = BeanUtil.toBean(bo, VideoInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean insertBatch(List<VideoInfo> list) {
        return baseMapper.insertBatch(list);
    }

    /**
     * 修改视频信息
     */
    @Override
    public Boolean updateByBo(VideoInfoBo bo) {
        VideoInfo update = BeanUtil.toBean(bo, VideoInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(VideoInfo entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除视频信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<VideoInfoVo> getRandomVideos(List<VideoInfoVo> videoInfoList, int count) {
        // 返回空列表，如果输入无效
        if (videoInfoList == null || count <= 0) {
            return new ArrayList<>();
        }
        if (videoInfoList.size() <= count) {
            return videoInfoList;
        }

        // 复制列表以避免改变原始列表
        List<VideoInfoVo> shuffledList = new ArrayList<>(videoInfoList);

        // 打乱列表顺序
        Collections.shuffle(shuffledList);

        // 截取前count个元素作为随机选取的结果
        return shuffledList.subList(0, Math.min(count, shuffledList.size()));
    }

    /**
     * 短视频首页
     */
    @Override
    public TableDataInfo<ShortVideoInfoVo> selectPageShortVideoList(ShortVideoInfoBo bo) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());

        Page<ShortVideoInfoVo> result = baseMapper.selectPageShortVideoList(pageQuery.build(), bo);
        for (ShortVideoInfoVo record : result.getRecords()) {

            // 判断是否点赞和收藏
            CollectionInfo collection = collectionMapper.selectOne(new LambdaUpdateWrapper<CollectionInfo>()
                    .eq(CollectionInfo::getCollectionId, record.getId())
                    .eq(CollectionInfo::getUserId, LoginHelper.getUserId())
                    .eq(CollectionInfo::getCollectionType, "0"));
            if (ObjectUtil.isNotNull(collection)) {
                record.setIsCollection("0");
            } else {
                record.setIsCollection("1");
            }
            UserLikeVo userLikeList = userLikeMapper.selectVoOne(new LambdaUpdateWrapper<UserLike>()
                    .eq(UserLike::getLikeTypeId, record.getId())
                    .eq(UserLike::getUserId, LoginHelper.getUserId())
                    .eq(UserLike::getLikeType, "0"));
            if (ObjectUtil.isNotNull(userLikeList)) {
                record.setIsGiveLike("0");
            } else {
                record.setIsGiveLike("1");
            }

            BuyOrder buyOrder = buyOrderService.queryByProductId(record.getId(), null, "1");
            if (ObjectUtil.isNotNull(buyOrder)) {
                record.setIsBuy("0");
            } else {
                record.setIsBuy("1");
            }

        }
        return TableDataInfo.build(result);
    }

    @Override
    public void updateBatchVideo(VideoInfoBo bo) {
        if (ArrayUtil.isNotEmpty(bo.getVideoIds())) {
            // 批量修改
            List<VideoInfo> list = StreamUtils.toList(Arrays.asList(bo.getVideoIds()), videoId -> {
                VideoInfo videoInfo = new VideoInfo();
                videoInfo.setId(videoId);
                videoInfo.setChargeType(bo.getChargeType());
                if ("2".equals(bo.getChargeType())) {
                    videoInfo.setConsumeDiamond(bo.getConsumeDiamond());
                }
                return videoInfo;
            });
            baseMapper.updateBatchById(list);
        }
    }

    @Override
    public void updateBatchUserVideo(VideoInfoBo bo) {
        if (ArrayUtil.isNotEmpty(bo.getVideoIds())) {
            // 批量修改
            List<VideoInfo> list = StreamUtils.toList(Arrays.asList(bo.getVideoIds()), videoId -> {
                VideoInfo videoInfo = new VideoInfo();
                videoInfo.setId(videoId);
                videoInfo.setShortVideoUserId(bo.getShortVideoUserId());
                return videoInfo;
            });
            baseMapper.updateBatchById(list);
        }
    }
}
